package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.common.BehaviorConstants;
import com.heima.behavior.service.ReadBehaviorService;
import com.heima.behavior.thread.AppThreadLocalUtil;
import com.heima.common.cache.CacheService;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

@Service
@Slf4j
/**
 *
 */
// @Primary
public class ReadBehaviorServiceImpl implements ReadBehaviorService {
	@Autowired
	private CacheService cacheService;
	
	@Override
	public ResponseResult read(ReadBehaviorDto dto) {
		//参数合法性判断
		if (dto == null) {
			return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
		}
		//获取用户登录状态
		ApUser currentUser = AppThreadLocalUtil.getUser();
		Integer currentUserId = currentUser.getId();
		if (currentUser == null || currentUserId == null) {
			return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
		}
		
		//提取常用参数
		Long articleId = dto.getArticleId();
		Short count = dto.getCount();
		
		//判断Redis中是否含有该文章数据
		String o = (String) cacheService.hGet(BehaviorConstants.READ_BEHAVIOR + articleId, currentUserId.toString());
		if (o != null) {
			ReadBehaviorDto readBehaviorDto = JSON.parseObject(o, ReadBehaviorDto.class);
			Short totalCount = readBehaviorDto.getCount();
			short newCount =  (short) (totalCount + count);
			dto.setCount(newCount);
		}
		
		//将新的文章喜欢数据存入redis
		cacheService.hPut(BehaviorConstants.READ_BEHAVIOR + articleId, currentUserId.toString(), JSON.toJSONString(dto));
		
		//返回
		return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
	}
	
}
